# -*- coding: utf8 -*-

import string
from puppy.result import ResultFilter

class BlackListResultFilter(ResultFilter):
  """
  Filters search results based on the results' suitability for children.
  
  Options:
  
  * threshold (double): confidence score to accept a page (e.g. 0.5)
  """
  
  def __init__(self, options=""):
    """Constructor for BlackListResultFilter."""
    super(BlackListResultFilter, self).__init__(options)
    self.info = "Filters search results based on a blacklist."
    self.black_list_string = " ".join(filter(str.isalpha, self.options['terms'].replace('+', ' ').lower().split()))
  
  def apply_black_list(self, input_string):
    """
    Replaces words in black list for *** characters.
    
    Parameters:
      
    * black_list_string: string with words included in the black list
    * input_string: string with words separated by blank spaces 
    
    Returns:
    
    * ouput_string: string of words separated by blank spaces which 
      words included in the black list has been replaced by ***          
    """
    input_list = input_string.split()
    output_string = input_string

    for input in input_list:  
      try:  
        input_filtered = "".join(filter(str.isalpha, list(input.lower())))
      except TypeError:
        tmp = input.encode("iso-8859-1").lower()
        input_filtered = "".join(filter(str.isalpha, list(tmp)))
             
      if input_filtered in self.black_list_string:
        if input_filtered not in ' ':
          output_string = output_string.replace(input, '***')
    return output_string

  def run(self, results):
    '''
    Filters the document list according to black list.
    
    Parameters:
      
    * results (puppy.model.Opensearch.Response): results to be filtered
    
    Returns:
    
    * results_returned (puppy.model.Opensearch.Response): filtered results
          
    '''    
    ''' black_list_string = self.options['terms'].replace('+', ' ') '''    
    
    
    results.title = self.apply_black_list(results.title)
    results.description = self.apply_black_list(results.description)
    
    for item in results.items:
      item.title = self.apply_black_list(item.title)
      item.description =  self.apply_black_list(item.description)
        
    # Return the filtered search result
    results_returned = results
    return results_returned
  
